package com.zmn.plat.business.impl.channel;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.engineer.dubbo.interfaces.engchannel.ChannelEngineerListRemoteService;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.business.interfaces.channel.ChannelBService;
import com.zmn.plat.business.interfaces.channel.ChannelCopyBService;
import com.zmn.plat.dubbo.utils.DubboConsts;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.model.entity.channel.Channel;
import com.zmn.plat.model.entity.channel.ChannelCopy;
import com.zmn.plat.model.entity.channel.ChannelQuery;
import com.zmn.plat.services.interfaces.channel.*;
import com.zmn.plat.services.interfaces.channel.brand.ratio.ChannelBrandRatioService;
import com.zmn.plat.services.interfaces.channel.commission.settle.rule.ChannelCommissionSettleRuleService;
import com.zmn.plat.services.interfaces.channel.generalproduct.ChannelGeneralProductSwitchService;
import com.zmn.plat.services.interfaces.channel.order.config.ChannelOrderConfigService;
import com.zmn.plat.services.interfaces.channel.product.map.ChannelProductMapService;
import com.zmn.plat.services.interfaces.channel.settle.ChannelMergeSettleService;
import com.zmn.plat.services.interfaces.channel.sp.ChannelSpService;
import com.zmn.plat.services.interfaces.channel.tariff.ChannelTariffService;
import com.zmn.plat.services.interfaces.channel.workorder.picture.ChannelWorkOrderPictureService;
import com.zmn.plat.services.interfaces.channel.workorder.video.ChannelWorkOrderVideoService;
import com.zmn.plat.services.interfaces.orderconfig.oderstock.channel.ChannelConfigCloseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 描述: 渠道复制实现类
 *
 * @author guoqiao
 * @since 2021/6/8 10:24
 */
@Service
@Slf4j
public class ChannelCopyBServiceImpl implements ChannelCopyBService {

    @Resource
    private ChannelService channelService;

    @Resource
    private ChannelBService channelBService;

    @Resource
    private ChannelOrderConfigService channelOrderConfigService;

    @Resource
    private ChannelWorkOrderPictureService channelWorkOrderPictureService;

    @Resource
    private ChannelWorkOrderVideoService channelWorkOrderVideoService;

    @Resource
    private ChannelServiceCategoryService channelServiceCategoryService;

    @Resource
    private ChannelGeneralProductSwitchService channelGeneralProductSwitchService;

    @Resource
    private ChannelServProductService channelServProductService;

    @Resource
    private ChannelProductMapService channelProductMapService;

    @Resource
    private ChannelServiceAreaService channelServiceAreaService;

    @Resource
    private ChannelServiceAreaCategoryService channelServiceAreaCategoryService;

    @Resource
    private ChannelConfigCloseService channelConfigCloseService;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ChannelEngineerListRemoteService channelEngineerListRemoteService;

    @Resource
    private ChannelSpService channelSpService;

    @Resource
    private ChannelTariffService channelTariffService;

    @Resource
    private ChannelCityPriceRatioService channelCityPriceRatioService;

    @Resource
    private ChannelBrandRatioService channelBrandRatioService;

    @Resource
    private ChannelCommissionService channelCommissionService;

    @Resource
    private ChannelCommissionSettleRuleService channelCommissionSettleRuleService;

    @Resource
    private ChannelDepositService channelDepositService;

    @Resource
    private ChannelDnisService channelDnisService;

    @Resource
    private ChannelMergeSettleService channelMergeSettleService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copyChannel(ChannelCopy copy, LoginStaff loginStaff) {
        String operator = loginStaff.getRealName();
        // 校验参数
        this.checkParams(copy);

        // 复制成为新渠道
        if (copy.getCopyType() == GlobalConsts.NO) {
            // 复制基本信息
            int targetChannelId = this.initChannelBase(copy, operator);
            if (NumberUtil.isNullOrZero(targetChannelId)) {
                throw new RuntimeException("复制异常！");
            }
            log.info("开始复制新渠道，原渠道id:{}，目标渠道id:{}", copy.getOriginalChannelId(), targetChannelId);
            // 复制订单配置
            channelOrderConfigService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制工单照片
            channelWorkOrderPictureService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制工单视频
            channelWorkOrderVideoService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制开通分类
            channelServiceCategoryService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制开通通用产品
            channelGeneralProductSwitchService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制开通产品
            channelServProductService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制产品映射关系
            channelProductMapService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制开通区域
            channelServiceAreaService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制区域开通分类
            channelServiceAreaCategoryService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制订单库存
            channelConfigCloseService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制服务工程师
            ResponseDTO<Boolean> booleanResponseDTO = channelEngineerListRemoteService.copyChannelEngineer(copy.getOriginalChannelId(), targetChannelId);
            if (!booleanResponseDTO.isSuccess()) {
                throw new RuntimeException("复制服务工程师异常！");
            }
            // 复制服务商
            channelSpService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制价格
            channelTariffService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制城市系数
            channelCityPriceRatioService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制品牌系数
            channelBrandRatioService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制佣金设置
            channelCommissionService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制佣金结算规则
            channelCommissionSettleRuleService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制结算信息
            channelDepositService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制押金
            channelDnisService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 复制合并结算渠道明细
            channelMergeSettleService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
            // 调用开通erp账户的接口
            channelBService.copyChannelSendChannelOpenAccount(targetChannelId, loginStaff);


        } else if (copy.getCopyType() == GlobalConsts.YES) {
            // 复制信息至现有渠道
            for (Integer targetChannelId : copy.getTargetChannelIdList()) {
                log.info("开始复制信息至现有渠道，原渠道id:{}，目标渠道id:{}", copy.getOriginalChannelId(), targetChannelId);
                if (copy.getRangeIdList().contains(GlobalConsts.NO)) {
                    // 复制工单视频
                    channelWorkOrderVideoService.deleteByChannelId(targetChannelId);
                    channelWorkOrderVideoService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
                }
                if (copy.getRangeIdList().contains(GlobalConsts.YES)) {
                    // 复制开通分类
                    channelServiceCategoryService.deleteByChannelId(targetChannelId, ProductDict.EC_PRODUCT_TYPE);
                    channelServiceCategoryService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
                    // 复制开通通用产品
                    channelGeneralProductSwitchService.deleteByChannelId(targetChannelId);
                    channelGeneralProductSwitchService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
                    // 复制开通产品
                    channelServProductService.deleteByChannelId(targetChannelId);
                    channelServProductService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
                    // 复制产品映射关系
                    channelProductMapService.deleteByChannelId(targetChannelId);
                    channelProductMapService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
                    // 复制开通区域
                    channelServiceAreaService.deleteByChannelId(targetChannelId);
                    channelServiceAreaService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
                    // 复制区域开通分类
                    channelServiceAreaCategoryService.deleteByChannelId(targetChannelId);
                    channelServiceAreaCategoryService.copy(copy.getOriginalChannelId(), targetChannelId, operator);
                }
            }
        }
    }

    /**
     * 描述: 校验参数合法性
     *
     * @param copy 入参
     * @author guoqiao
     * @since 2021/6/24 10:15
     */
    private void checkParams(ChannelCopy copy) {

        if (copy == null && NumberUtil.isNullOrZero(copy.getOriginalChannelId()) && NumberUtil.isNullOrZero(copy.getCopyType())) {
            throw new IllegalArgumentException("参数不合法");
        }
        // 复制成为新渠道
        if (copy.getCopyType() == GlobalConsts.NO) {
            if (StringUtil.isBlank(copy.getNewChannelName())) {
                throw new IllegalArgumentException("新渠道名称为空");
            }
            // 校验名称是否存在
            ChannelQuery query = new ChannelQuery();
            query.setName(copy.getNewChannelName());
            List<Channel> channels = channelService.listByQuery(query);
            if (!CollectionUtils.isEmpty(channels)) {
                throw new RuntimeException("新渠道名称已存在");
            }
        } else if (copy.getCopyType() == GlobalConsts.YES) {
            // 复制信息至现有渠道
            if (CollectionUtils.isEmpty(copy.getTargetChannelIdList())) {
                throw new IllegalArgumentException("目标渠道为空！");
            }
            if (copy.getTargetChannelIdList().contains(copy.getOriginalChannelId())) {
                throw new IllegalArgumentException("目标渠道包含原渠道！");
            }
            if (CollectionUtils.isEmpty(copy.getRangeIdList())) {
                throw new IllegalArgumentException("复制范围为空！");
            }
        }
    }

    /**
     * 描述: 初始化复制渠道基本信息
     *
     * @param copy 复制渠道入参
     * @return operator 操作者
     * @author guoqiao
     * @since 2021/6/24 10:22
     */
    private int initChannelBase(ChannelCopy copy, String operator) {

        Channel channel = channelService.findByKey(copy.getOriginalChannelId());
        channel.setChannelId(null);
        channel.setName(copy.getNewChannelName());
        channel.setAnotherName(null);
        channel.setAnotherNamePinyin(null);
        channel.setCreater(operator);
        channel.setCreateTime(new Date());
        channel.setUpdater(operator);
        channel.setUpdateTime(new Date());
        channelService.insert(channel);
        return channel.getChannelId();
    }

}
